`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module csr_mepc
(
    input           sys_clk,
    
    input           i_irq_src,
    input           i_exp_src,
    input [ 31: 0 ] i_exe_pc,
    
    input           i_acc_dis,
    input [ 11: 0 ] i_csr_addr,
    input [ 31: 0 ] i_csr_val,
    input           i_csr_wen,
    
    output [ 31: 0 ] o_mepc,

    input           rst_n
);
/*
mepc : Machine Exception Program Counter   RW
*/

wire [ 31: 0 ]  i_mepc;
wire [ 31: 0 ]  mepc_r;
/*
assign i_mepc = i_irq_src ? ( i_exe_pc + 4 ) :
                      ( i_exp_src ? i_exe_pc : mepc_r );
*/

wire mepc_valid = (i_irq_src | i_exp_src) ? 1'b1 : 1'b0;
assign i_mepc = mepc_valid ? i_exe_pc : mepc_r;

wire wbck_csr_wen = i_csr_wen & ( ~i_acc_dis );

//0x341 MRW mepc Machine exception program counter.
wire sel_mepc = ( i_csr_addr == 12'h341 );
wire wr_mepc = sel_mepc & wbck_csr_wen;
wire mepc_ena = wr_mepc | mepc_valid;

wire [ 31: 0 ] mepc_nxt;
assign mepc_nxt[ 31: 1 ] = mepc_valid ? i_mepc[ 31 : 1 ] : i_csr_val[ 31 : 1 ];
assign mepc_nxt[ 0 ] = 1'b0; // have to be 1'b0, otherwise  will generate the misalign exception according to ISA

yue_dfflr #( 32 ) epc_dfflr ( mepc_ena, mepc_nxt, mepc_r, sys_clk, rst_n );
assign o_mepc = mepc_r;

endmodule
